package org.oimwrapper.connectors.common;

import org.oimwrapper.connectors.*;

/**
 * Deletes task instances that do not have an undo task associated with 
 * them.<p>
 *
 * This task expects the following parameters, in addition to the standard
 * parameters in the {@link OIMTaskBase} class.
 * <ul>
 * <li><code>TaskName</code> The name of a the tasks to delete instances of.  This name can include wild cards.</li>
 * </ul>
 */
public class OIMDeleteNonUndoableTaskInstances extends OIMTaskBase {

	/**
	 * True if a stop has been requested for this task.
	 */
	private boolean stop;

	/**
	 * Default constructor.
	 */
	public OIMDeleteNonUndoableTaskInstances() {
		super("OIMWRAPPER.TASK");
		stop = false;
	}

	/**
	 * This method is called by the scheduler to execute the task instance.
	 */
	public void execute() {
		try {
			logger.warn("Clearing all non-undoable task instances...");
			String taskName = getDefaultAttribute("TaskName", "*");
			if (!stop) {
				logger.info("Clearing OSI...");
				executeOimQuery("delete from osi where mil_key not in (select mil_key from unm) and mil_key not in (select unm_undo_mil_key from unm) and mil_key not in (select mil_key from mil where mil_required_complete=1) and sch_key in (select sch_key from sch where sch_status in ('C', 'UC', 'MC', 'X')) and mil_key in (select mil_key from mil where mil_name like '" + taskName.replaceAll("\\*", "%") + "')");
				logger.info("Deleted records from OSI");
			}
			if (!stop) {	
				logger.info("Clearing OSH...");
				executeOimQuery("delete from osh where sch_key not in (select sch_key from osi)");
				logger.info("Deleted records from OSH");
			}
			if (!stop) {	
				logger.info("Clearing SCH...");
				executeOimQuery("delete from sch where sch_key not in (select sch_key from osi) and sch_key not in (select osi_retry_for from osi where osi_retry_for is not null)");
				logger.info("Deleted records from SCH");
			}
			logger.warn("All non-undoable task instances have been cleared.");
		} catch (Exception e) {
			OIMExceptionHandler.handleException(logger, e, getClass());
		}
	}

	/**
	 * This method is called by the scheduler to stop a running task instance.
	 * 
	 * @return <code>true</code>
	 */
	public boolean stop() {
		logger.warn(" ---- Stopping current task ---- ");
		stop = true;
		return stop;
	}
}